﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using AHD.MyNes.Nes;
using System.Threading;
using System.Windows.Media.Imaging;

namespace SilverNes
{
	public partial class MainPage : UserControl
	{
		public MainPage()
		{
			InitializeComponent();
			renderTarget.Source = buffer;
		}

		private NesEmulator nes;
		private object nesLock = new object();
		private WriteableBitmap buffer = new WriteableBitmap(Video.Width, Video.Height);

		private void Render()
		{
			
		}


		private void OpenRom(string fileName)
		{
			NesEmulator nes = new NesEmulator();

			nes.InitializeEngine();
			nes.LoadCart(fileName);

			nes.LimitTo50 = true;

			// nes.myPPU.LoadPalette();
			var myThreadCreator = new ThreadStart(nes.DoFrame);
			var gameThread = new Thread(myThreadCreator);
			gameThread.Start();

			nes.isPaused = false;

			lock (nesLock)
			{
				this.nes = nes;
			}
		}

		private void renderTarget_KeyDown(object sender, KeyEventArgs e)
		{
			Key key = e.Key;
			HandleKey(key, true);
		}

		private void HandleKey(Key key, bool down)
		{
			lock (nesLock)
			{
				if (nes != null)
				{
					switch (key)
					{
					case Key.Left:
						nes.myJoypad.Left = down;
						break;
					case Key.Right:
						nes.myJoypad.Right = down;
						break;
					case Key.Up:
						nes.myJoypad.Up = down;
						break;
					case Key.Down:
						nes.myJoypad.Down = down;
						break;

					case Key.Z:
						nes.myJoypad.B = down;
						break;
					case Key.X:
						nes.myJoypad.A = down;
						break;

					case Key.Enter:
						nes.myJoypad.Start = down;
						break;
					case Key.S:
						nes.myJoypad.Select = down;
						break;

					// TODO: other keys
					}
				}
			}
		}

		private void renderTarget_KeyUp(object sender, KeyEventArgs e)
		{
			Key key = e.Key;
			HandleKey(key, false);
		}
	}
}
